package com.example.cdpbookstore.web.servlet;


import com.example.cdpbookstore.pojo.entity.CartItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@WebServlet("/quantity-inc-dec")
public class QuantityIncDecServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        Long id = Long.valueOf(request.getParameter("id"));
        List<CartItem> cart = (List<CartItem>) request.getSession().getAttribute("cart");

        if (action != null && id >= 1) {
            if (action.equals("inc")) {
                for (CartItem item : cart) {
                    if (Objects.equals(item.getBook().getId(), id)) {
                        item.setQuantity(item.getQuantity() + 1);
                        break;
                    }
                }
            }

            if (action.equals("dec")) {
                for (CartItem item : cart) {
                    if (Objects.equals(item.getBook().getId(), id) && item.getQuantity() > 1) {
                        item.setQuantity(item.getQuantity() - 1);
                        break;
                    }
                }
            }
        }

        response.sendRedirect("shopping-cart.jsp");

    }
}
